#include<linux/fs.h>
#include<linux/uaccess.h>  
#include<asm/io.h> 
#include<linux/device.h>   
#include <linux/module.h>
#include"led_opr.h"




unsigned int major;
static struct class *led_class;
struct led_opr *p_led_fops;

int led_drv_open(struct inode *inode, struct file *file)
{
    int minor = iminor(inode);
	printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);

	/* 根据次设备号初始化LED */
	p_led_fops->init(minor);
	
	return 0;
}


static ssize_t led_drv_write(struct file *file, const char *user_buf, size_t count,loff_t *ppos)
{
    int ret;
	char status;
	struct inode *inode = file_inode(file);
	int minor = iminor(inode);
	
	printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
	ret = copy_from_user(&status, user_buf, 1);

	/* 根据次设备号和status控制LED */
	p_led_fops->ctl(minor, status);
	
	return 0;
}


static const struct file_operations led_drv_fops = {
    .owner = THIS_MODULE,
	.open  = led_drv_open,
	.write = led_drv_write,
};
	
static int led_drv_init(void)
{
    int i;
	printk("%s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
	/* 注册一个字符设备 */
	 major = register_chrdev(0, "myled", &led_drv_fops);
	/* 创建一个设备节点 */
	led_class = class_create(THIS_MODULE, "myled"); 
    /* 获取开发板led的operations */
     p_led_fops = get_led_fops();
	/*根据开发板中LED的个数，创建设备/dev/led0,led1... */
	for(i = 0; i < p_led_fops->num; i++)
	device_create(led_class, NULL, MKDEV(major, i), NULL, "myled"); 
	
	return 0;
}
static void led_drv_exit(void)
{
	  int i;
	  /* 删除设备节点 */
	  for(i = 0; i < p_led_fops->num; i++)
	  device_destroy(led_class,  MKDEV(major, i));
	  
	  class_destroy(led_class);

	   /* 注销字符设备 */
	   unregister_chrdev(major, "myled");
}

module_init(led_drv_init);
module_exit(led_drv_exit);
MODULE_LICENSE("GPL");



